package com.omuao.message.websocket.controller;

import com.omuao.message.websocket.config.RocketMqProcessor;
import com.omuao.message.websocket.error.ServiceException;
import com.omuao.message.websocket.facade.MqttWebSocketService;
import com.omuao.message.websocket.facade.WebSocketMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * MQTT web socket 控制器（EMQ X）
 *
 * @author omuao
 */
@RestController
@RequestMapping("/emq/x/socket")
@EnableBinding(RocketMqProcessor.class)
public class MqttWebSocketController {

    @Autowired
    MqttWebSocketService mqttWebSocketService;

    /**
     * 消息发布
     *
     * @param webSocketMessage 消息
     */
    @StreamListener(RocketMqProcessor.NOTIFY_INPUT)
    public void message(WebSocketMessage webSocketMessage) throws ServiceException {
        mqttWebSocketService.insert(webSocketMessage);
    }

    /**
     * 消息发布
     *
     * @param map
     */
    @PostMapping("/hook")
    public void hook(@RequestBody Map<String, Object> map) throws ServiceException {
        mqttWebSocketService.processHookEvent(map);
    }

    /**
     * 鉴权
     *
     * @param username 用户名
     * @param password 密码
     * @param clientId 客户端ID
     */
    @PostMapping("/auth")
    public void auth(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("clientid") String clientId, HttpServletResponse response) {
        boolean flag = mqttWebSocketService.auth(username, password, clientId);
        if (flag) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }

    /**
     * 发送离线消息
     */
    @Scheduled(fixedRate = 1)
    public void sendOfflineMessage() throws ServiceException {
        mqttWebSocketService.sendOfflineMessage();
    }
}
